//
//  AsyncConnection.m
//  ProjectForA
//
//  Created by hmengwei on 14/11/19.
//  Copyright (c) 2014年 hmengwei. All rights reserved.
//

#import "AsyncConnection.h"

@implementation AsyncConnection

- (void)dealloc
{
    [super dealloc];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.recivData = [NSMutableData data];
    }
    return self;
}

+(void)getConnectWithUrl:(NSString *)url value:(NSDictionary *)value block:(FinishedBlock)block
{
    AsyncConnection *connect = [[AsyncConnection alloc] init];
    connect.finishedBlock = block;
    [connect startWithUrl:url value:value block:block];
    [connect release];
}


-(void)startWithUrl:(NSString *)url value:(NSDictionary *)value block:(FinishedBlock)block
{
    NSString *urlStr = @"";
    if (value != nil) {
        for (NSString *key in value) {
            if ([urlStr length] == 0) {
                urlStr = [NSString stringWithFormat:@"?%@=%@", key, [value objectForKey:key]];
            } else
            {
                urlStr = [NSString stringWithFormat:@"%@&%@=%@", urlStr, key, [value objectForKey:key]];
            }
            
        }
        NSString *resultUrl = [NSString stringWithFormat:@"%@%@", url, urlStr];
        NSURL *nsurl = [NSURL URLWithString:resultUrl];
        NSMutableURLRequest *resquest = [NSMutableURLRequest requestWithURL:nsurl];
        [resquest setHTTPMethod:@"GET"];
        [NSURLConnection connectionWithRequest:resquest delegate:self];
    } else
    {
        NSURL *nsurl = [NSURL URLWithString:url];
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:nsurl];
        
        [request setHTTPMethod:@"GET"];
        
        [NSURLConnection connectionWithRequest:request delegate:self];
    }
    
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.recivData appendData:data];

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.finishedBlock(_recivData);
}



@end
